#include "Render.h"
#include <string>



CRender::CRender(void)
{
	m_pDevice = NULL;
	m_pMesh = NULL;

	srand(GetTickCount());
}


CRender::~CRender(void)
{
}


void CRender::Init(IDirect3DDevice9* m_pDevice, HWND wnd)
{

	//	Create mesh
	m_pMesh = new CMesh("meshes/terrain.x", m_pDevice);

	m_Camera.Init(m_pDevice);

	//	Create light
	ZeroMemory(&m_Light, sizeof(m_Light));
	m_Light.Type      = D3DLIGHT_DIRECTIONAL;
	m_Light.Ambient   = D3DXCOLOR(0.5, 0.5, 0.5, 1.0f);
	m_Light.Diffuse   = D3DXCOLOR(0.9, 0.9, 0.9, 1.0f);
	m_Light.Specular  = D3DXCOLOR(0.5, 0.5, 0.5, 1.0f);
	m_Light.Direction = D3DXVECTOR3(0.7f, -0.3f, 0.0f);
	m_pDevice->SetLight(0, &m_Light);
	m_pDevice->LightEnable(0, true);

	//	Set sampler state
	for(int nSample = 0; nSample < 4; nSample++)
	{
		m_pDevice->SetSamplerState(nSample, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
		m_pDevice->SetSamplerState(nSample, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
		m_pDevice->SetSamplerState(nSample, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
	}

}
void CRender::Update(float fDTime, IDirect3DDevice9* m_pDevice)
{
	D3DXMATRIX matWorld;
	D3DXMatrixIdentity(&matWorld);
	m_pDevice->SetTransform(D3DTS_WORLD, &matWorld);

	//	Update Camera
	m_Camera.Update(fDTime);

	if(KEYDOWN(VK_ESCAPE))
	{
		Quit();
	}

}

HRESULT CRender::Render(IDirect3DDevice9* m_pDevice)
{

	// clear the viewport
	m_pDevice->Clear(0L , NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 1.0f, 0L); 



	if(SUCCEEDED(m_pDevice->BeginScene()))
	{
		//////////////////////////////////////////////////////////////////////////
		//							RENDER MESH									//
		//////////////////////////////////////////////////////////////////////////
		if(m_pMesh != NULL)
			m_pMesh->Render();


		// End the scene.
		m_pDevice->EndScene();
		m_pDevice->Present(0, 0, 0, 0);
	}
	return S_OK;
}
void CRender::Cleanup()
{
	try
	{
		if(m_pMesh != NULL)
		{
			delete m_pMesh;
			m_pMesh = NULL;
		}
	}
	catch (...)
	{

	}

}
void CRender::Quit()
{

	PostQuitMessage(0);
}

